/**
 * @Author 12629
 * @Description：
 */
public class HashBuck {

    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array ;
    public int usedSize;//记录 当前哈希桶当中 有效数据的个数
    //默认的负载因子
    public static final float DEFAULT_LOAD_FACTOR = 0.75F;

    public HashBuck() {
        this.array = new Node[10];
        this.usedSize = 0;
    }

    /**
     * 存储key val
     * @param key
     * @param val
     */
    public void put(int key,int val) {
        Node node = new Node(key,val);
        int index = key % array.length;

        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //头插法
        node.next = array[index];
        array[index] = node;
        usedSize++;

        //检查负载因子
        if(loadFactor() >= DEFAULT_LOAD_FACTOR) {
            //进行 扩容
            grow();
        }

    }

    private float loadFactor() {
        return usedSize*1.0f / array.length;
    }

    private void grow() {
        Node[] newArray = new Node[2* array.length];
        //重新的哈希
        /**
         * 1. 遍历数组的每个元素的链表
         * 2. 每遍历到一个节点，就重新哈希  key % len
         * 3. 进行头插法
         */
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                //找到新的位置
                int index = cur.key % newArray.length;
                cur.next = newArray[index];
                newArray[index] = cur;
                //这样写对吗？
                //cur = cur.next;
                cur = curNext;
            }
        }
        this.array = newArray;
    }

    /**
     * 通过key值 获取val 值
     * @param key
     * @return
     */
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
